const WebSocket = require("ws")
const dataHandler = require("../data_handler")
const HG = require("./hg.js")
require("../config/global_config")

var eventFun = new Map();

function createServer() {
    // 创建websocket服务
    const server = new WebSocket.Server({ port: 8000, path: "/hg" }, () => {
        global.log("websocket服务器正在监听8000端口")
    })
    // 连接时
    server.on("connection", (ws, req) => {
        let ip = ws._socket.remoteAddress.replace("::ffff:", "");
        let p = getParamer(req.url)
        let username = p["username"]
        let hg1 = global.account.hg1;
        let hg2 = global.account.hg2;
        // 如果是没有带账号的连接，则说明皇冠没有登录，然后去获取账号 
        if ((!username || username == "undefined")) {
            let setting = false;
            if (!hg1.status && !setting) {
                setting = hg1
            }
            if (!hg2.status && !setting) {
                setting = hg1
            }
            global.log("开始登录,分配账号：" + setting.username)
            ws.username = setting.username
            ws.send(JSON.stringify({
                action: "user",
                result: {
                    username: setting.username,
                    password: setting.password
                }
            }))
        } else {
            // 如果是带用户名连接的，则检查当前登录用户是否和配置一样
            if (username != hg1.username && username != hg2.username) {
                global.log("连接的账号不正确，断开连接：" + username)
                ws.close();
                return;
            }
            if (username == hg1.username) {
                hg1.status = true;
                hg2.status = false;
            }
            if (username == hg2.username) {
                hg2.status = true;
                hg1.status = false;
            }
            ws.username = username;
            global.log("连接的账号正确，开始监听：" + username)
        }
        global.ws = ws;
        ws.on("message", msg => {
            setImmediate(() => {
                messageHandler(ws, msg, username)
            })
        })
        ws.on("error", err => {
            global.log("服务器错误:", err.message)
        })
        ws.on("close", () => {
            global.log("客户端关闭：" + ws.username + ` | ${ip}`)
        })
    })
    loopData()
}

function messageHandler(ws, msg, username) {
    try {
        let str = msg.toString()
        json = JSON.parse(str)
        if (json.result && username) {
            let fn = eventFun.get(json.action)
            if (fn) {
                fn(json.result, username)
            }
            return
        }
    } catch (err) {
        global.log(`账号[${ws.username}]发生未知异常:${err.message}`)
    }
}

function getParamer(url) {
    let pam = url.split("?")[1]
    let pams = pam.split("&")
    let result = {}
    for (let i = 0; i < pams.length; i++) {
        let p = pams[i]
        let r = p.split("=")
        result[r[0]] = r[1]
    }
    return result;
}


eventFun.set("hg_status", function (data) {
    // global.info(data)
})

eventFun.set("order_end", function (data) {
    global.info("下单成功，新增历史记录:" + JSON.stringify(data))

})


eventFun.set("game_list", function (data) {
    if (data && data.list.length > 0) {
        console.info(`HG获取到 ${data.list.length} 场比赛数据`)
        dataHandler.update_hga_data(data.list);
    }
})

global.AccountMap = new Map();

eventFun.set("info", function (data, username) {
    let hg = new HG(data, username);
    global.AccountMap.set(username, hg)
})

var lastLang = "zh-cn"
var hgUpudateTime = 0; // 上次更新HG数据的时间

createServer()

function loopData() {
    try {
        global.AccountMap.forEach((value, key) => {
            lastLang = lastLang === 'zh-cn' ? 'en-us' : lastLang === 'en-us' ? 'zh-cn' : "en-us"; // 切换语言 
            value.start(lastLang)
        })
        hgUpudateTime = Date.now(); // 更新上次更新时间
    } catch (err) {
        global.log("HG数据循环异常:", err.message)
    }
    setTimeout(() => {
        loopData()
    }, 5000);
}
// 